package com.ch.fastbuilder.common;

import java.sql.Connection;
import java.sql.SQLException;

public class LocalConnetionManager {

    private static final ThreadLocal<Connection> autoConnection = new ThreadLocal<Connection>();
    private static final ThreadLocal<Connection> handConnection = new ThreadLocal<Connection>();
    
    private LocalConnetionManager() {
        super();
    }

    public static void setAutoConnection(Connection connection) {
    	autoConnection.set(connection);
    }
    
    public static Connection getAutoConnection() {
        return autoConnection.get();
    }
    
    public static void removeAutoConnection() {
    	autoConnection.remove();
    }
    
    public static void setHandConnection(Connection connection) {
    	handConnection.set(connection);
    }
    
    public static Connection getHandConnection() {
        return handConnection.get();
    }
    
    public static void removeHandConnection() {
    	handConnection.remove();
    }
    
    public static void closeAutoConnection() {
    	Connection conn = LocalConnetionManager.getAutoConnection();
    	if(conn != null) {
    		try {
				if(!conn.isClosed()) conn.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
    		conn = null;
    	}
    	LocalConnetionManager.removeAutoConnection();
    }
    
    public static void closeHandConnection() {
    	Connection conn = LocalConnetionManager.getHandConnection();
    	if(conn != null) {
    		try {
				if(!conn.isClosed()) conn.close();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
    		conn = null;
    	}
    	LocalConnetionManager.removeHandConnection();
    }
}
